#!/bin/bash

scripts_root="/home/pi/siweather/scripts"
PATH="$PATH:/home/pi/siweather/scripts:/usr/sbin:/bin:/usr/bin"

maestro_dir="/home/pi/siweather/maestro"

connected=`$maestro_dir/./UscCmd --list 2>&1 | grep Maestro | awk '{ print $1}'`
if [ $connected -lt 1 ]; then echo "No Maestro servo controller found!"; exit 1; fi

CAM=`lsusb | grep Canon`

if [ -n "$CAM" ]; then
        echo "Camera already on"
	exit 0
fi

time_limit=6
seconds=0

$maestro_dir/./UscCmd --servo 3,8000 &> /dev/null
sleep 1
$maestro_dir/./UscCmd --servo 3,0000 &> /dev/null
sleep 1

while [ -z "$CAM" -a $seconds -lt $time_limit ]; do
	sleep 1
	seconds=`expr $seconds + 1`
	CAM=`/usr/bin/lsusb | grep Canon`
done

if [ -z "$CAM" ]; then
	echo "First attempt to turn on camera failed, trying again..."
else
	echo "Camera turned on after "$seconds" seconds."
	sleep 4
	exit 0
fi

COUNT=1
LIM=20

while [ -z "$CAM" -a $COUNT -lt $LIM ]; do
	COUNT=`expr $COUNT + 1`
	$maestro_dir/./UscCmd --servo 3,8000 &> /dev/null
	sleep 1
	$maestro_dir/./UscCmd --servo 3,0000 &> /dev/null
	sleep 6
	CAM=`/usr/bin/lsusb | grep Canon`
	CAM=`/usr/bin/lsusb | grep Canon`
done

if [ $COUNT -lt $LIM ]; then
	echo "Camera turned on after "$COUNT" attempts."
	echo "On "`date`", the camera needed "$COUNT" attempts to switch on." >> /home/pi/logs/cam_switch_log
	sleep 4
	exit 0
else 
	echo "Failed to turn on the camera after "$LIM" attempts."
	echo "On "`date`", the camera failed to turn on after "$LIM" attempts." >> /home/pi/logs/cam_switch_log
	exit 1
fi

exit 0
